﻿using Freebase4net.Rest;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Freebase4net
{
    public class ServicesHelpers
    {
        public static RestClient CreateRequest(dynamic query, string apiKey)
        {
            var parseToMql = new MqlParser(query);
            RestClient client = new RestClient { BaseUrl = Constants.MqlReadServiceUrl };

            client.AddParameter("query", parseToMql.JsonString);

            if (!string.IsNullOrEmpty(apiKey))
            {
                client.AddParameter("key", apiKey);
            }

            client.RequestFormat = DataFormat.Json;
            return client;
        }

        public static MqlReadServiceResponse CreateResponse(RestResponseMessage response)
        {
            var freebaseResponse = new MqlReadServiceResponse
            {
                ResultAsString = response.Content,
                Status = response.StatusCode
            };

            if (freebaseResponse.Status == System.Net.HttpStatusCode.OK)
            {
                var resultList = (JArray)JObject.Parse(response.Content)["result"];
                foreach (var item in resultList)
                {
                    freebaseResponse.Results.Add((dynamic)item);
                }
            }

            return freebaseResponse;
        }

        public static string GetImageMode(ImageServiceMode mode)
        {
            switch (mode)
            {
                case ImageServiceMode.Fit:
                    return "fit";
                case ImageServiceMode.Fill:
                    return "fill";
                case ImageServiceMode.FillCrop:
                    return "fillcrop";
                case ImageServiceMode.FillCropMid:
                    return "fillcropmid";
                default:
                    return "";
            }
        }

        public static string GetTextFormat(TextFormat format)
        {
            switch (format)
            {
                case TextFormat.Plain:
                    return "plain";
                case TextFormat.Html:
                    return "html";
                default:
                    return "raw";
            }
        }

        public static string GetUniquenessFailure(UniquenessFailure failure)
        {
            switch (failure)
            {
                case UniquenessFailure.Hard:
                    return "hard";
                case UniquenessFailure.Soft:
                    return "soft";
                default:
                    return "";
            }
        }
    }
}
